package com.ruoyi.project.lely.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.R;
import com.ruoyi.framework.aspectj.lang.annotation.DataSource;
import com.ruoyi.framework.aspectj.lang.enums.DataSourceType;
import com.ruoyi.project.lely.bean.dto.LyWechatLoginDTO;
import com.ruoyi.project.lely.bean.entity.LyUser;
import com.ruoyi.project.lely.bean.vo.LyWechatLoginVO;
import com.ruoyi.project.lely.constant.CommonConstant;
import com.ruoyi.project.lely.service.LyUserService;
import com.ruoyi.project.lely.service.LyWechatService;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Desc: 微信相关
 * @Author LuoYong
 * @Date 2022/1/22 12:48
 */
@Service
@Slf4j
@DataSource(value = DataSourceType.SLAVE)
public class LyWechatServiceImpl implements LyWechatService {

    @Autowired
    private WxMaService wxService;
    @Autowired
    private LyUserService userService;


    @Override
    public R login(LyWechatLoginDTO dto) {
        String sessionKey = null;
        String openId = null;
        try {
            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(dto.getCode());
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (sessionKey == null || openId == null) {
            log.error("微信登录,调用官方接口失败：{}", dto.getCode());
            return R.fail();
        }

        LyUser user = userService.getOne(
                new LambdaQueryWrapper<LyUser>()
                        .eq(LyUser::getWeixinOpenid, openId)
                        .eq(LyUser::getDeleted, CommonConstant.DELETED)
        );
        if (user == null) {
            user = new LyUser();
            user.setUsername(openId);
            user.setPassword(openId);
            user.setWeixinOpenid(openId);
            user.setAvatar(dto.getAvatarUrl());
            user.setNickname(dto.getNickName());
            user.setGender(dto.getGender());
            user.setUserLevel(0);
            user.setStatus(0);
            user.setDeleted(0);

            // 新用户发送注册优惠券
            // couponAssignService.assignForRegister(user.getId());
        }
        user.setLastLoginTime(LocalDateTime.now());
        user.setLastLoginIp("127.0.0.1");
        userService.saveOrUpdate(user);

        LyWechatLoginVO vo = new LyWechatLoginVO();
        vo.setUserInfo(user);
        vo.setToken("123456");

        // token
        // UserToken userToken = null;
        // try {
        //     userToken = UserTokenManager.generateToken(user.getId());
        // } catch (Exception e) {
        //     logger.error("微信登录失败,生成token失败：{}", user.getId());
        //     e.printStackTrace();
        //     return R.fail();
        // }
        // userToken.setSessionKey(sessionKey);
        //
        // Map<Object, Object> result = new HashMap<Object, Object>();
        // result.put("token", userToken.getToken());
        // result.put("tokenExpire", userToken.getExpireTime().toString());
        // userInfo.setUserId(user.getId());
        // if (!StringUtils.isEmpty(user.getMobile())) {// 手机号存在则设置
        //     userInfo.setPhone(user.getMobile());
        // }
        // try {
        //     String registerDate = DateTimeFormatter.ofPattern("yyyy-MM-dd")
        //             .format(user.getAddTime() != null ? user.getAddTime() : LocalDateTime.now());
        //     userInfo.setRegisterDate(registerDate);
        //     userInfo.setStatus(user.getStatus());
        //     userInfo.setUserLevel(user.getUserLevel());// 用户层级
        //     userInfo.setUserLevelDesc(UserTypeEnum.getInstance(user.getUserLevel()).getDesc());// 用户层级描述
        // } catch (Exception e) {
        //     logger.error("微信登录：设置用户指定信息出错："+e.getMessage());
        //     e.printStackTrace();
        // }
        // result.put("userInfo", userInfo);

        return R.ok(vo);
    }
}
